require 'digest/sha1'
class SessionHash < ActiveRecord::Base
  
  validates_presence_of :token
  validates_uniqueness_of :token
  
  before_save :create_token
  
  def create_token
    self.token ||= generate_token
  end
  
  private
  def generate_token
    5.times do
      token = Digest::SHA1.hexdigest(rand + Time.now)
      return token unless SessionHash.find_by_token(token)
    end
    return nil
  end
end
